package cn.edu.hstc.wm.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import cn.edu.hstc.wm.AppApplication;
import cn.edu.hstc.wm.AppConfigs;
import cn.edu.hstc.wm.Constants;
import cn.edu.hstc.wm.R;
import cn.edu.hstc.wm.adapter.StoreCommentAdapter;
import cn.edu.hstc.wm.bean.Comment;
import cn.edu.hstc.wm.bean.Store;
import cn.edu.hstc.wm.service.AppConfigService;
import cn.edu.hstc.wm.service.CommentService;
import cn.edu.hstc.wm.ui.StoreItemActivity;
import cn.edu.hstc.wm.ui.base.BaseFragment;
import cn.edu.hstc.wm.utils.LogUtil;
import cn.edu.hstc.wm.widget.CustomToast;
import cn.edu.hstc.wm.widget.XListView;
import cn.edu.hstc.wm.widget.XListView.IXListViewListener;

import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 进入店铺后显示店铺信息的Fragment
 */
public class StoreItemInfo extends BaseFragment implements OnClickListener, IXListViewListener {
	public static final String TAG = "StoreItemInfo";
	public static final String INTENT_URL = "StoreItemInfo";

	private View mRootView = null;
	/** 店铺图标 */
	private ImageView storeIcon;
	/** 店铺名 */
	private TextView storeName;
	/** 店铺评分条 */
	private RatingBar storeGrade;
	/** 店铺收藏 */
	private ImageView storeFav;
	/** 店铺用户评分 */
	private TextView storeUserGrade;
	/** 速度 */
	private TextView storeSpeed;
	/** 起送价 */
	private TextView storeStartPrice;
	/** 服务费 */
	private TextView storeServerPrice;
	/** 店铺简介 */
	private TextView storeIntroduce;
	/** 店铺支持服务 */
	private ImageView supportPhone, supportSMS, supportReserve, supportSend;
	/** 联系电话 */
	private TextView longNumber, shortNumber;
	/** 营业时间 */
	private TextView storeTime;
	/** 店铺地址 */
	private TextView address;
	/** 我要评论 */
	private TextView goComment;
	/** 还没有评论 */
	private TextView noComment;

	/** 用户评论 */
	private XListView mCommentListView;
	private StoreCommentAdapter mAdapter;

	/** 该店铺 */
	private Store mStore;
	/** 该店铺的评论集合 */
	private List<Comment> mComments;

	/** 当前最后一个数据所在的位置 */
	private int mCurDataIndex = 0;
	/** 最大的位置 */
	private int mMaxIndex = 0;

	private Handler mHandler;

	/**
	 * 获取StoreItemInfo Fragment的实例的方法
	 * 
	 * @param bundle
	 * @return
	 */
	public static StoreItemInfo getInstance(Bundle bundle) {
		StoreItemInfo storeItemInfo = new StoreItemInfo();
		storeItemInfo.setArguments(bundle);
		return storeItemInfo;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mRootView = inflater.inflate(R.layout.store_item_info_fragment_layout, null);
		mHandler = new Handler();

		getData();
		initView();
		setView();
		initCommentView();
		return mRootView;
	}

	private void initView() {
		storeIcon = (ImageView) mRootView.findViewById(R.id.iv_store_item_info_icon);
		storeName = (TextView) mRootView.findViewById(R.id.tv_store_item_info_title);
		storeGrade = (RatingBar) mRootView.findViewById(R.id.ratingbar_store_item_info_grade);
		storeFav = (ImageView) mRootView.findViewById(R.id.iv_store_item_info_favorite);
		storeUserGrade = (TextView) mRootView.findViewById(R.id.tv_store_item_info_grade);
		storeSpeed = (TextView) mRootView.findViewById(R.id.tv_store_item_info_speed);
		storeStartPrice = (TextView) mRootView.findViewById(R.id.tv_store_item_info_start_price);
		storeServerPrice = (TextView) mRootView.findViewById(R.id.tv_store_item_info_server);
		storeIntroduce = (TextView) mRootView.findViewById(R.id.tv_store_item_info_introduce);
		supportPhone = (ImageView) mRootView.findViewById(R.id.iv_store_support_phone);
		supportSMS = (ImageView) mRootView.findViewById(R.id.iv_store_support_sms);
		supportReserve = (ImageView) mRootView.findViewById(R.id.iv_store_support_reserve);
		supportSend = (ImageView) mRootView.findViewById(R.id.iv_store_support_send);
		longNumber = (TextView) mRootView.findViewById(R.id.tv_store_item_info_long_number);
		shortNumber = (TextView) mRootView.findViewById(R.id.tv_store_item_info_short_number);
		storeTime = (TextView) mRootView.findViewById(R.id.tv_store_item_info_shop_time);
		address = (TextView) mRootView.findViewById(R.id.tv_store_item_info_address);
		goComment = (TextView) mRootView.findViewById(R.id.tv_store_item_info_go_comment);
		mCommentListView = (XListView) mRootView.findViewById(R.id.xListView_store_item_info_user_comment);
		noComment = (TextView) mRootView.findViewById(R.id.tv_store_item_info_no_comment);
	}

	/** 获取store数据 */
	private void getData() {
		mStore = (Store) getArguments().getSerializable(StoreItemActivity.INTENT_URL);
		// 获取评论个数
		new GetCommentCountTask().execute(mStore.getId());
	}

	private void setView() {
		storeName.setText(mStore.getName());
		if (!mStore.getImageName().equals(Constants.DEFAULT_IMG) && AppConfigService.isLoadImage(getActivity())) {
			ImageLoader.getInstance().displayImage(AppConfigs.STORE_IMAGE_URL + mStore.getImageName(), storeIcon);
		} else {
			storeIcon.setImageResource(R.drawable.default_no_img);
		}
		storeGrade.setRating((float) mStore.getScore());
		// TODO 用户收藏
		storeFav.setSelected(false);

		storeUserGrade.setText(mStore.getScore() + "");
		storeSpeed.setText(mStore.getSpeed() + "");

		if (!String.valueOf(mStore.getStart_price()).equals("-1")) {
			storeStartPrice.setText(mStore.getStart_price() + "");
		} else {
			storeStartPrice.setText("暂无");
		}
		if (!String.valueOf(mStore.getSend_price()).equals("-1")) {
			storeServerPrice.setText(mStore.getSend_price() + "");
		} else {
			storeServerPrice.setText("暂无");
		}

		storeIntroduce.setText(mStore.getIntrodution() + "");

		// 是否支持
		supportPhone.setEnabled(mStore.getSuport_call() == 1);
		supportReserve.setEnabled(mStore.getSuport_order() == 1);
		supportSMS.setEnabled(mStore.getSuport_SMS() == 1);
		supportSend.setEnabled(mStore.getSuport_send() == 1);

		// 联系电话
		longNumber.setText(mStore.getLong_number());
		shortNumber.setText(mStore.getShort_number());

		// 营业时间
		storeTime.setText(mStore.getShop_time());
		address.setText(mStore.getAddress());

		// 收藏,去评论监听
		storeFav.setOnClickListener(this);
		goComment.setOnClickListener(this);
		noComment.setOnClickListener(this);
	}

	/** 初始化评论View */
	private void initCommentView() {
		mComments = new ArrayList<Comment>();
		mAdapter = new StoreCommentAdapter(getActivity(), mComments);
		mCommentListView.setAdapter(mAdapter);
		mCommentListView.setPullLoadEnable(true);
		mCommentListView.setPullRefreshEnable(true);
		mCommentListView.setXListViewListener(this);

		// Utility.setListViewHeightBasedOnChildren(userComment);
	}

	/**
	 * 设置是否显示评论内容
	 * 
	 * @param flag
	 *            true : 显示评论内容,隐藏'还没有评论' ; false : 显示'还没有评论',隐藏评论内容
	 */
	private void setCommentViewShow(boolean flag) {
		// 还没有评论
		if (mMaxIndex == 0 && !flag) {
			noComment.setVisibility(View.VISIBLE);
			mCommentListView.setVisibility(View.GONE);
		}
		// 有评论
		else if (flag && mMaxIndex > 0) {
			// Utility.setListViewHeightBasedOnChildren(mCommentListView);
			mCommentListView.setVisibility(View.VISIBLE);
			noComment.setVisibility(View.GONE);
		}
	}

	private void getCommentData(int index) {
		// 不再加载数据了 ,提示没有更多了
		if (index >= mMaxIndex) {
			CustomToast.make(getActivity()).setText("已经到最末尾了").show();
			return;
		}
		// 符合加载条件,继续加载数据
		else {
			new GetCommentTask().execute(index);
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	public void onRefresh() {
		// 刷新数据
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				mComments.clear();
				mCurDataIndex = 0;
				getCommentData(mCurDataIndex);
				onLoad();
			}
		}, 1500);

	}

	public void onLoadMore() {
		// 加载更多
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				getCommentData(mCurDataIndex);
				onLoad();
			}
		}, 1500);
	}

	@SuppressLint("SimpleDateFormat")
	public void onLoad() {
		mCommentListView.stopRefresh();
		mCommentListView.stopLoadMore();
		mCommentListView.setRefreshTime(new SimpleDateFormat("HH:mm:ss") // 更新时间设置
				.format(new Date(System.currentTimeMillis())) + "");
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.tv_store_item_info_no_comment:
			// 我要评论
		case R.id.tv_store_item_info_go_comment:
			// 已经登录
			if (((AppApplication) getActivity().getApplication()).isLogin()) {
				Bundle bundle = new Bundle();
				bundle.putSerializable(INTENT_URL, mStore);
				GoCommentDialog.newInstance(bundle).show(getFragmentManager(), "评论");
			} else {
				CustomToast.make(getActivity()).setText("还没登录,请先登录再评价").show();
			}
			break;

		// 点击收藏
		case R.id.iv_store_item_info_favorite:
			if (!((AppApplication) getActivity().getApplication()).isLogin()) {
				CustomToast.make(getActivity()).setText("请先登录再收藏").show();
			} else {
				if (storeFav.isSelected()) {
					// 取消收藏
					CustomToast.make(getActivity()).setText("取消收藏").show();
					storeFav.setSelected(false);
					// TODO User favorite -->false
				} else {
					// 添加收藏
					CustomToast.make(getActivity()).setText("已收藏").show();
					storeFav.setSelected(true);
					// TODO User favorite -->true
				}
			}
			break;

		default:
			break;
		}

	}

	/**
	 * 获取该店铺的评论的异步方法类
	 * 
	 */
	private final class GetCommentTask extends AsyncTask<Integer, Integer, List<Comment>> {

		@Override
		protected List<Comment> doInBackground(Integer... params) {
			try {
				// store id , 起始位置 , 每次加载个数
				return CommentService.getCommentsByStoreId(mStore.getId(), params[0], AppConfigService.getItemCount(getActivity()));
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPreExecute() {
			LogUtil.d(TAG, "GetCommentTask start");
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(List<Comment> result) {
			if (result != null) {
				mComments.addAll(result);
				mCurDataIndex = mCurDataIndex + result.size();
				mAdapter.notifyDataSetChanged();
				setCommentViewShow(true);
			} else {
				// 加载失败
				CustomToast.make(getActivity()).setText("Sorry 加载失败 !-_-").show();
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		protected void onCancelled(List<Comment> result) {
			super.onCancelled(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

	}

	/**
	 * 获取店铺评论个数的任务
	 * 
	 */
	private final class GetCommentCountTask extends AsyncTask<Integer, Integer, Integer> {

		@Override
		protected Integer doInBackground(Integer... params) {
			try {
				return CommentService.getCommentsCountByStoreId(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}

		@Override
		protected void onPreExecute() {
			LogUtil.d(TAG, "GetCommentCount start");
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (result != 0) {
				LogUtil.d(TAG, "GetCommentCount end ,result = " + result);
				mMaxIndex = result;
				setCommentViewShow(true);
				getCommentData(mCurDataIndex);
			} else {
				setCommentViewShow(false);
			}
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		protected void onCancelled(Integer result) {
			// TODO Auto-generated method stub
			super.onCancelled(result);
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

	}

}
